package com.huiminpay.paymentagent.message;

import com.alibaba.fastjson.JSON;
import com.huiminpay.paymentagent.api.PayChannelAgentService;
import com.huiminpay.paymentagent.api.conf.AliConfigParam;
import com.huiminpay.paymentagent.api.conf.WXConfigParam;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.paymentagent.api.dto.TradeStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;

import javax.annotation.Resource;

/**
 * 消息监听类,消费消息
 */
@Service
@Slf4j
@RocketMQMessageListener(topic = "TP_PAYMENT_ORDER", consumerGroup = "CID_PAYMENT_CONSUMER")
public class PayConsumer implements RocketMQListener<MessageExt> {
    @Resource
    PayChannelAgentService payChannelAgentService;

    @Resource
    PayProducer payProducer;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        String jsonString = new String(body);
        log.info("支付渠道代理服务接收到查询订单的消息:{}", JSON.toJSONString(jsonString));
        //将消息转化为对象
        PaymentResponseDTO paymentResponseDTO = JSON.parseObject(jsonString, PaymentResponseDTO.class);
        String outTradeNo = paymentResponseDTO.getOutTradeNo(); //订单号
        String params = String.valueOf(paymentResponseDTO.getContent()); //支付渠道参数

        PaymentResponseDTO responseDTO = null;

        if ("ALIPAY_WAP".equals(paymentResponseDTO.getMsg())) {
            //调用支付宝订单状态查询接口
            //params转为对象
            AliConfigParam aliConfigParam = JSON.parseObject(params, AliConfigParam.class);
            responseDTO = payChannelAgentService.queryPayOrderByAliWAP(aliConfigParam, outTradeNo);
        } else if ("WX_JSAPI".equals(paymentResponseDTO.getMsg())) {
            //调用微信接口去查询订单状态
            WXConfigParam wxConfigParam = JSON.parseObject(params, WXConfigParam.class);
        }

        //当没有获取到订单结果，抛出异常，再次消费信息
        if (responseDTO == null || TradeStatus.UNKNOWN.equals(responseDTO.getTradeState()) ||
                TradeStatus.USERPAYING.equals(responseDTO.getTradeState())) {
            log.info("支付代理‐‐‐支付状态未知，等待重试");
            throw new RuntimeException("支付状态未知，等待重试");
        }
        //不管支付成功还是失败都需要发送支付结果消息
        log.info("交易中心处理支付结果通知，支付代理发送消息:{}", responseDTO);
        payProducer.payResultNotice(responseDTO);
    }
}
